package com.java_foundation.thread_demo.test_6;

/**
 * @program: java_foundation
 * @description: wait函数
 * @author: xiongbangwen <Email>xiongbangwen@163.com</Email>
 * @create: 2020-06-21 16:29
 **/
public class WaitDemo {
    //创建资源
    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    Thread threadA = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                synchronized (resourceA) {
                    System.out.println("线程A获取resourceA的监视器锁");
                    synchronized (resourceB) {
                        System.out.println("线程A获取resourceB的监视器锁");
                        System.out.println("线程A阻塞并释放获取到的resourceA的监视器锁");
                        resourceA.wait();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }); Thread threadB = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);//睡眠1S，让A先拿到锁
                synchronized (resourceA) {
                    System.out.println("线程B获取resourceA的监视器锁");
                    synchronized (resourceB) {
                        System.out.println("线程B获取resourceB的监视器锁");
                        System.out.println("线程B阻塞并释放获取到的resourceA的监视器锁");
                        resourceA.wait();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}
